<?php

namespace App\Http\Controllers;

use App\Library\HandleIntegral;
use App\Library\HandleIntegralExchange;
use App\Models\Coupon;
use App\Models\Goods;
use App\Models\IntegralKill;
use App\Models\MallOrder;
use App\Models\User;
use DB;
use Exception;
use Illuminate\Http\Request;

/**
 * 积分商城相关
 */
class IntegralController extends Controller
{
    /**
     * 积分商城首页
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function integral_index(Request $request)
    {
        try {
            $status  = 0;
            $data    = [];
            $user_id = $request->get('user_id');
            if (empty($user_id)) {
                throw new Exception('缺少参数');
            }
            $user = User::where('userID', $user_id)->first();
            if (!$user) {
                throw new Exception('未找到用户');
            }
            $data['user_id']         = $user_id;
            $data['nickname']        = $user->nickname;
            $data['headimg']         = $user->headimg;
            $data['integral']        = $user->integral;
            $data['expire_integral'] = HandleIntegral::entry($user_id);
            $data['expire_time']     = date('Y-m-d', strtotime(date('Y-12-31 23:59:59')));

            $status = 1;
            $msg    = '查询成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 今日新品
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function new_product(Request $request)
    {
        try {
            $status = 0;
            $data   = [];
            $limit  = $request->get('limit') ?? 4;
            //从积分秒杀表里查询今日新品
            $kills = IntegralKill::where(['is_delete' => 0, 'is_new' => 1])
                ->where('bg_time', '<', time())
                ->where('end_time', '>', time())
                ->orderBy('create_time', 'desc')->limit($limit)->get();

            //处理数据(商品名称，商品图片，所需积分，是否秒杀)
            foreach ($kills as $key => $value) {
                $arr               = [];
                $arr['goods_id']   = $value->goods_id;
                $arr['goods_type'] = $value->goods_type;
                $arr['integral']   = $value->integral;
                $arr['closed']     = $value->closed;
                if ($value->goods_type == 1) {
                    //实物商品
                    $goods        = Goods::where(['goods_id' => $value->goods_id])->first();
                    $arr['name']  = $goods->name;
                    $arr['photo'] = $goods->photo;
                } else {
                    $coupon       = Coupon::where(['coupon_id' => $value->goods_id])->first();
                    $arr['name']  = $coupon->coupon_name;
                    $arr['photo'] = $coupon->photo;
                }
                $data[$key] = $arr;
            }

            $status = 1;
            $msg    = '查询成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 券礼包
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function gift_bag(Request $request)
    {
        try {
            $status = 0;
            $data   = [];
            $limit  = $request->get('limit') ?? 4;
            $kills  = IntegralKill::where(['is_delete' => 0, 'goods_type' => 2])
            //->where('bg_time', '<', time())
            //->where('end_time', '>', time())
                ->orderBy('create_time', 'desc')->limit($limit)->get();
            //处理数据
            foreach ($kills as $key => $value) {
                $data[$key]['goods_id'] = $value->goods_id;
                $data[$key]['integral'] = $value->integral;
                $data[$key]['closed']   = $value->closed;
                $coupon                 = Coupon::where(['coupon_id' => $value->goods_id])->first();
                $data[$key]['name']     = $coupon->coupon_name;
                $data[$key]['photo']    = $coupon->photo;
            }

            $status = 1;
            $msg    = '查询成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 积分秒杀
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function second_kill(Request $request)
    {
        try {
            $status = 0;
            $data   = [];
            $limit  = $request->get('limit') ?? 4;
            //从积分秒杀表里查询今日新品
            $kills = IntegralKill::where(['is_delete' => 0, 'closed' => 2])
            //->where('bg_time', '<', time())
            //->where('end_time', '>', time())
                ->orderBy('create_time', 'desc')->limit($limit)->get();

            //处理数据(商品名称，商品图片，所需积分，是否秒杀)
            foreach ($kills as $key => $value) {
                $arr               = [];
                $arr['goods_id']   = $value->goods_id;
                $arr['goods_type'] = $value->goods_type;
                $arr['integral']   = $value->integral;
                if ($value->goods_type == 1) {
                    //实物商品
                    $goods        = Goods::where(['goods_id' => $value->goods_id])->first();
                    $arr['name']  = $goods->name;
                    $arr['photo'] = $goods->photo;
                } else {
                    $coupon       = Coupon::where(['coupon_id' => $value->goods_id])->first();
                    $arr['name']  = $coupon->coupon_name;
                    $arr['photo'] = $coupon->photo;
                }
                $data[$key] = $arr;
            }
            $status = 1;
            $msg    = '查询成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 积分兑换
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function integral_exchange(Request $request)
    {
        try {
            $status  = 0;
            $data    = [];
            $user_id = $request->get('user_id');
            $kill_id = $request->get('kill_id');
            if (empty($user_id) || empty($kill_id)) {
                throw new Exception('缺少参数');
            }
            //开启事务
            DB::beginTransaction();

            $exchange = new HandleIntegralExchange($user_id, $kill_id);
            $res      = $exchange->entry();

            if ($res['status'] == 0) {
                throw new Exception($res['msg']);
            }
            DB::commit();
            $order = MallOrder::where(['order_id' => $res['data']['order_id']])->first();
            //处理数据
            $data['order_id']      = $order->order_id;
            $data['integral']      = $order->integral;
            $data['time']          = date('Y-m-d H:i:s', $order->create_time);
            $data['postage']       = $order->postage;
            $data['delivery_type'] = $order->delivery_type;
            $data['order_num']     = $order->order_num;
            $data['order_type']    = '积分兑换';
            if ($order->goods_type == 1) {
                $data['name']      = $order->goods->name;
                $data['introduce'] = $order->goods->introduce;
                $data['photo']     = $order->goods->photo;
            } else {
                $data['name']      = $order->coupon->coupon_name;
                $data['introduce'] = $order->coupon->introduce;
                $data['photo']     = $order->coupon->photo;
            }

            $status = 1;
            $msg    = '操作成功';
        } catch (Exception $e) {
            DB::rollback();
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 完善收货地址
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function perfect_order(Request $request)
    {
        try {
            $status     = 0;
            $data       = [];
            $address_id = $request->get('address_id');
            $kill_id    = $request->get('kill_id');
            if (empty($address_id) || empty($kill_id)) {
                throw new Exception('缺少参数');
            }
            //更新积分订单收货地址信息
            MallOrder::where(['kill_id' => $kill_id])->update([
                'address_id' => $address_id,
            ]);
            $status             = 1;
            $msg                = '提交成功';
            $data['address_id'] = $address_id;
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 我的兑换纪录
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function exchange_list(Request $request)
    {
        try {
            $status  = 0;
            $data    = [];
            $user_id = $request->get('user_id');
            if (empty($user_id)) {
                throw new Exception('缺少参数');
            }
            //兑换纪录
            $orders = MallOrder::where([
                'user_id' => $user_id, 'order_type' => 1, 'is_delete' => 0,
            ])->orderBy('create_time', 'desc')->paginate(5);
            //处理数据
            foreach ($orders as $key => $value) {
                $data[$key]['goods_type'] = $value->goods_type;
                $data[$key]['order_type'] = $value->order_type;
                //商品名称和图片
                if ($value->goods_type == 1) {
                    //实物
                    $data[$key]['name']  = $value->goods->name;
                    $data[$key]['photo'] = $value->goods->photo;
                } else {
                    $data[$key]['name']  = $value->coupon->coupon_name;
                    $data[$key]['photo'] = $value->coupon->photo;
                }
                $data[$key]['expire_time'] = date('Y-m-d', $value->integral_kill->end_time);
            }

            $status = 1;
            $msg    = '操作成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }
}
